from flask_apscheduler import APScheduler
from .task_func import task_clear_book_info, task_print
from databases import HandleDb, db_configs

# import json
scheduler = APScheduler()

task_func_list = [
    {
        "title": "task_clear_book_info",
        "func": task_clear_book_info,
        "role": "该任务用来清除不存在的书内容和目录"
    },
    {
        "title": "task_print",
        "func": task_print,
        "role": "该任务用来测试的"
    }
]


def start_init():
    # 程序启动时 这里初始化任务
    db = HandleDb(**db_configs.LOCALHOST_DB_FLASK_DEMO_CONFIG)
    result = db.find("task")
    if type(result) == list:
        for item in result:
            task_id = item['task_id']
            task_func_name = item['task_func_name']
            task_state = item['state']
            task_params = eval(item['task_params'])
            task_type = item['task_type']
            task_name = item['task_name']
            job = scheduler.get_job(task_id)
            if job:
                continue
            try:
                for task_func_item in task_func_list:
                    if task_func_item['title'] == task_func_name:
                        scheduler.add_job(id=task_id, name=task_name, args=(task_id,task_name), func=task_func_item['func'],
                                          trigger=task_type, **task_params)
                        if task_state == 'start':
                            continue
                        scheduler.pause_job(task_id)
            except Exception as e:
                print(e)
    print(scheduler.get_jobs())
